using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Web;

namespace LetLord.Models
{ 
    public class LandlordRepository : ILandlordRepository
    {
        LetLordContext context = new LetLordContext();

        public IQueryable<Landlord> All
        {
            get { return context.UserProfile.OfType<Landlord>(); }
        }

        public IQueryable<Landlord> AllIncluding(params Expression<Func<Landlord, object>>[] includeProperties)
        {
            IQueryable<Landlord> query = context.UserProfile.OfType<Landlord>();
            foreach (var includeProperty in includeProperties) {
                query = query.Include(includeProperty);
            }
            return query;
        }

        public Landlord Find(int id)
        {
            return context.UserProfile.OfType<Landlord>().SingleOrDefault(t => t.UserId == id);
        }

        public Landlord GetLoggedInLandlord()
        {
            return context.UserProfile.OfType<Landlord>().First(l => l.UserName == System.Web.HttpContext.Current.User.Identity.Name);
        }

        public void InsertOrUpdate(Landlord landlord)
        {
            if (landlord.UserId == default(int)) {
                // New entity
                context.Set<Landlord>().Add(landlord);
            } else {
                // Existing entity
                context.Entry(landlord).State = EntityState.Modified;
            }
        }

        public void Delete(int id)
        {
            var landlord = context.UserProfile.OfType<Landlord>().SingleOrDefault(t => t.UserId == id);
            context.Set<Landlord>().Remove(landlord);
        }

        public byte[] GetPropertyPhoto(int id)
        {
            PropertyPhoto pp = context.Image.OfType<PropertyPhoto>().SingleOrDefault(x => x.ImageId == id);
            if (pp != null)
            {
                byte[] image = pp.File;
                return image;
            }
            else
            {
                throw new ArgumentException("Error retrieving image");
            }
        }

        public void Save()
        {
            context.SaveChanges();
        }

        public void Dispose() 
        {
            context.Dispose();
        }
    }

    public interface ILandlordRepository : IDisposable
    {
        IQueryable<Landlord> All { get; }
        IQueryable<Landlord> AllIncluding(params Expression<Func<Landlord, object>>[] includeProperties);
        Landlord Find(int id);
        Landlord GetLoggedInLandlord();
        byte[] GetPropertyPhoto(int id);
        void InsertOrUpdate(Landlord landlord);
        void Delete(int id);
        void Save();
    }
}